package cn.yunyichina.provider.bone.listener;

import cn.yunyichina.provider.bone.service.impl.BoneMsgServiceImpl;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.XmlUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.listener.MessageListener;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/2/10.
 */
public class BoneOperationWechatPayMessageListener  implements MessageListener<Integer, String> {
    private Logger logger = LoggerFactory.getLogger(BoneOperationWechatPayMessageListener.class);

    @Override
    public void onMessage(ConsumerRecord<Integer, String> integerStringConsumerRecord) {
        String xmlString = integerStringConsumerRecord.value();
        logger.info("骨科手术单回调, 入参xmlString = " + xmlString);

        try {
            Map<String, String> doc = XmlUtils.xmlToMap(xmlString);
            String orderNo = doc.get("out_trade_no");
            String openId = doc.get("openid");
            String appId = doc.get("appid");
            String transactionId = doc.get("transaction_id");
            String attach = doc.get("attach");
            JSONObject jsonObj = JSONObject.parseObject(attach);
            String payMode = jsonObj.getString("pay_mode");
            // Float payAmount = Float.parseFloat((String) doc.get("total_fee"));
            BigDecimal payAmount = new BigDecimal( doc.get("total_fee")).multiply(new BigDecimal(100));

            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("order_no", orderNo);
            logger.info("骨科手术单回调, 订单号" + orderNo + ", 调base模块, 查询订单信息入参request=" + JSONObject.toJSONString(dataMap));
            Response ordResponse = BaseService.callUnderlineFromInternal("", "yyt.base.order.by.order.no.out.get",
                    JsonUtils.toJsonString(dataMap));
            logger.info("骨科手术单回调, 订单号" + orderNo + ", 调base模块, 查询订单信息返回response=" + JSONObject.toJSONString(ordResponse));
            if("0".equals(ordResponse.getResultCode())) {
                OrderExtVo vo = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
                vo.setPayTime(DateUtils.dateToString(new Date()));
                vo.setUpdateTime(DateUtils.dateToString(new Date()));
                // 96：已缴手术费
                vo.setOrderStatus((short) 96);
                // 已支付
                vo.setPayStatusPayed();
                vo.setPayAppId(appId);
                vo.setPayMode(Short.parseShort(payMode));
                // 支付流水
                vo.setPaymentDealId(transactionId);
                logger.info("骨科手术单回调, 订单号" + orderNo + ", 调base模块, 更新订单信息入参request=" + JSONObject.toJSONString(vo));
                BaseService.callUnderlineFromInternal("", "yyt.base.order.update", JsonUtils.toJsonString(vo));
                
                // 发送推送消息
                sendMessage(vo,openId);
            } else {
                logger.info("骨科手术单回调, 订单号" + orderNo + ", 调base模块, 查不到该订单.");
            }
        } catch (Exception e) {
            logger.error("骨科手术单回调报错", e);
        }
        logger.info("骨科手术单回调处理结束.");
    }
    
	// 发送微信通知
	private void sendMessage(OrderExtVo vo,String openId) {
		logger.info("骨科问诊/押金单回调, 发送推送消息");
		try {
			final BoneMsgServiceImpl boneMsgService = SpringContextHandler.getBean("boneMsgServiceImpl");
            final JSONObject request=new JSONObject();
            request.put("order_no",vo.getOrderNo());
            request.put("app_id",vo.getPayAppId());
            request.put("open_id",openId);
			// 患者支付手术费完成
			new Thread(new Runnable() {

				@Override
				public void run() {
					// 发送微信给患者
					logger.info("发送微信通知给患者");
					boneMsgService.sendBoneMsgSurgeryArrangeOrder(request.toJSONString());
				}
			}).start();
		} catch (Exception e) {
			logger.error("骨科问诊/押金单回调, 发送推送消息异常", e);
		}
	}
}
